# coding: utf8

"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
@auth.requires_login()
def index():
    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))
    elif problem.lastmodified > problem.lastresponses[auth.user_id]:
        session.flash = "Items have changed. Please update your "\
        "responses before viewing the results page."

        redirect(URL(r=request, c='respond', f='index'))

    ## c,s are dicts containing criteria and solution responses
    c,s,sc,wsc, nmax, srankingd, crankingd = currentEvaluations(problem)
    #sys.stderr.write("%s\n"%repr(sc))
      
    return dict(problem=problem,c=c,s=s,sc=sc, wsc=wsc,
                problemid=session.problemid,
                nmax=nmax,
                )

@auth.requires_login()
def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    #session.forget()
    return service()

@auth.requires_login()
@service.json
def servecomments(problemid,itemid):
    debug("servecomments called ...")
    getcmts = ptproblem.getComments
    problem = loadProblem(problemid)
    if problem==None:
        raise ValueError
    if itemid == "problem":
        ## get comments from problem description
        cdict = getcmts(problem)
    elif itemid.startswith("solution"):
        ## get comments for requested solution
        cdict = getcmts(problem.solutions[itemid])
    elif itemid.startswith("criterion"):
        ## get comments for requested criterion
        cdict = getcmts(problem.criteria[itemid])
    else:
        raise ValueError("Invalid itemid %s"%itemid)

    keys = cdict.keys()
    keys.sort()    ## by timestamp,ascending
    
    comments = []
    for t in keys:
        comments.append(formatcomment(t,cdict[t]))
    return dict(n=len(comments), comments=comments)

@auth.requires_login()
@service.json
def serveresults(problemid,lastmodified,lastresponse): 
    data = request.args
    debug("serveresults called. args=%s"%repr(data))
    problem = loadProblem(problemid)
    if problem==None:
        raise ValueError
    ## c,s are dicts containing criteria and solution responses
    c,s,sc,wsc, nmax, srankingd, crankingd = currentEvaluations(problem)
    ## Convert to histograms suitable for plotting 
    for cid in c.keys():
        c[cid] = ptproblem.hist(c[cid],nbins=5, twosided=False)
    for sid in s.keys():
        s[sid] = ptproblem.hist(s[sid], nbins=9, twosided=True)
    for sid,cdict in sc.iteritems():
        for cid in cdict.keys():
            cdict[cid] = ptproblem.hist(cdict[cid], nbins=9, twosided=True)        
    for sid,cdict in wsc.iteritems():
        for cid in cdict.keys():
            cdict[cid] = ptproblem.hist(cdict[cid], nbins=9, twosided=True) 
    delvotes = problem.tallyDeletionVotes() 

    return dict(c=c, s=s, sc=sc, wsc=wsc, 
                nparticipants=len(problem.lastresponses),
                delvotes=delvotes, nmax=nmax, 
                srankingd=srankingd, 
                crankingd=crankingd,
                lastmodified=problem.lastmodified,
                lastresponse=max(problem.lastresponses.values()),
                )


def currentEvaluations(problem):
    """ Utility wrapper for problem.computeCurrentEvaluations()
        that returns the results with keys that are suitable to
        be element id's in rendered pages.
    """    
    #import time
    #t = time.time()
    c,s,sc,wsc, nmax = problem.computeCurrentEvaluations()
    #dt = time.time() - t
    #debug("%f seconds to compute evaluations"%dt)
    srankingd = dict()
    crankingd = dict()

    for sid,score in problem.srankings:    
        srankingd[sid] = score
    for cid,score in problem.crankings:
        crankingd[cid] = score
    return c,s,sc,wsc, nmax, srankingd, crankingd
